package org.jeecgframework.web.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyEsItemServiceI;
import org.jeecgframework.web.system.pojo.base.ZyEquipmentTypeEntity;
import org.jeecgframework.web.system.pojo.base.ZyEsItemEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;



/**   
 * @Title: Controller
 * @Description: 设备ITEM
 * @author onlineGenerator
 * @date 2016-05-25 15:10:22
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/zyEsItemController")
public class ZyEsItemController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ZyEsItemController.class);

	@Autowired
	private ZyEsItemServiceI zyEsItemService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ZyCommonService zyCommonService;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 设备ITEM列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "zyEsItem")
	public ModelAndView zyEsItem(HttpServletRequest request) {
		return new ModelAndView("com/zybk/zy_es_item/zyEsItemList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(ZyEsItemEntity zyEsItem,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyEsItemEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyEsItem, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.zyEsItemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 设备ITEM新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(ZyEsItemEntity zyEsItem, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyEsItem.getId())) {
			zyEsItem = zyEsItemService.getEntity(ZyEsItemEntity.class, zyEsItem.getId());
			req.setAttribute("zyEsItemPage", zyEsItem);
		}
		return new ModelAndView("com/zybk/zy_es_item/zyEsItem-add");
	}
	

	/**
	 * 添加设备ITEM
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(ZyEsItemEntity zyEsItem, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "设备ITEM添加成功";
		try{
			zyEsItemService.save(zyEsItem);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "设备ITEM添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	
	
	
	/**
	 * @author xiul
	 * 2016-5-25 下午5:00:42
	 * Description 设备item - 选择设备类型，单选
	 * @param request
	 * @return
	 */
	@RequestMapping(params="goChooseEquipmentType")
	public ModelAndView goChooseEquipmentType(HttpServletRequest request){
		return new ModelAndView("com/zybk/zy_es_item/zyChooseEquipmentTypeForEsItem");
	}
	/**
	 * @author xiul
	 * 2016-5-25 下午5:00:42
	 * Description 设备item - 选择设备类型，可以多选
	 * @param request
	 * @return
	 */
	@RequestMapping(params="goChooseEquipmentTypeCheckbox")
	public ModelAndView goChooseEquipmentTypeCheckbox(HttpServletRequest request){
		return new ModelAndView("com/zybk/zy_es_item/zyChooseEquipmentTypeForEsItemCheckBox");
	}

	/**
	 * @author xiul
	 * 2016-5-25 下午5:00:42
	 * Description 设备item - 选择设备类型datagrid加载
	 * @param zyEquipmentTypeEntity
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params="dataGridOfChooseEquipmentType")
	@ResponseBody
	public List<TreeGrid> dataGridOfChooseEquipmentType(ZyEquipmentTypeEntity zyEquipmentTypeEntity,HttpServletRequest request,HttpServletResponse response,TreeGrid treegrid){
		CriteriaQuery cq;
		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
		cq = new CriteriaQuery(ZyEquipmentTypeEntity.class);
		if (treegrid.getId() != null) {
			cq.eq("equipmentType.id", treegrid.getId());
		}else if(treegrid.getId() == null){
			cq.isNull("equipmentType.id");
		}
		cq.add();
        List<ZyEquipmentTypeEntity> ZyEquipmentTypeList = systemService.getListByCriteriaQuery(cq, false);
        TreeGridModel treeGridModel = new TreeGridModel();
        treeGridModel.setIdField("id");
		treeGridModel.setTextField("typeDesc");
		treeGridModel.setParentId("equipmentType_id");
		treeGridModel.setParentText("equipmentType_typeDesc");
		treeGridModel.setSrc("");
		treeGridModel.setChildList("childEquipmentTypes");
		treeGrids = systemService.treegrid(ZyEquipmentTypeList, treeGridModel);
		return treeGrids;
	}
	
	
	
	/**
	 * 设备ITEM编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(ZyEsItemEntity zyEsItem, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyEsItem.getId())) {
			zyEsItem = zyEsItemService.getEntity(ZyEsItemEntity.class, zyEsItem.getId());
//			if(StringUtil.isNotEmpty(zyEsItem.getType())){
//				ZyEquipmentTypeEntity zyEType = systemService.getEntity(ZyEquipmentTypeEntity.class, zyEsItem.getType());
//				req.setAttribute("typeVal", zyEType.getTypeDesc());
//			}
			req.setAttribute("zyEsItemPage", zyEsItem);
		}
		return new ModelAndView("com/zybk/zy_es_item/zyEsItem-update");
	}
	
	/**
	 * 更新设备ITEM
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(ZyEsItemEntity zyEsItem, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "设备ITEM更新成功";
		ZyEsItemEntity t = zyEsItemService.get(ZyEsItemEntity.class, zyEsItem.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(zyEsItem, t);
			zyEsItemService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "设备ITEM更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * @author xiul
	 * 2016-6-27 上午10:33:53
	 * Description 检查设备Item item唯一性
	 * @param param 设备 item
	 * @param eiId 设备Item ID
	 */
	@ResponseBody
	@RequestMapping(params="checkItemUnique")
	public ValidForm checkItemUnique(@RequestParam(value="param",defaultValue="")String param,
			@RequestParam(value="eiId",defaultValue="")String eiId
			){
		ValidForm vf = new ValidForm();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT COUNT(1) AS total ");
		sql.append(" FROM zy_es_item ei");
		sql.append(" WHERE ");
		sql.append(" ei.item = '"+param+"' ");
		if(StringUtil.isNotEmpty(eiId)){
			sql.append(" AND ei.id != '"+eiId+"' ");
		}
		int total = zyCommonService.getCountBySql(sql.toString());
		if(total > 0){
			vf.setStatus(ValidForm.N);
			vf.setInfo("当前item已经存在");
		}
		return vf;
	}
	
	/**
	 * 删除设备ITEM
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(ZyEsItemEntity zyEsItem, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		zyEsItem = systemService.getEntity(ZyEsItemEntity.class, zyEsItem.getId());
		message = "设备ITEM删除成功";
		try{
			zyEsItemService.delete(zyEsItem);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "设备ITEM删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除设备ITEM
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		message = "设备ITEM删除成功";
		try{
			for(String id:ids.split(",")){
				ZyEsItemEntity zyEsItem = systemService.getEntity(ZyEsItemEntity.class, 
				id
				);
				zyEsItemService.delete(zyEsItem);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "设备ITEM删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		return new ModelAndView("com/zybk/zy_es_item/zyEsItemUpload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(ZyEsItemEntity zyEsItem,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(ZyEsItemEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyEsItem, request.getParameterMap());
		List<ZyEsItemEntity> zyEsItems = this.zyEsItemService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"设备ITEM");
		modelMap.put(NormalExcelConstants.CLASS,ZyEsItemEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("设备ITEM列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,zyEsItems);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(ZyEsItemEntity zyEsItem,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		modelMap.put(TemplateExcelConstants.FILE_NAME, "设备ITEM");
		modelMap.put(TemplateExcelConstants.PARAMS,new TemplateExportParams("Excel模板地址"));
		modelMap.put(TemplateExcelConstants.MAP_DATA,null);
		modelMap.put(TemplateExcelConstants.CLASS,ZyEsItemEntity.class);
		modelMap.put(TemplateExcelConstants.LIST_DATA,null);
		return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<ZyEsItemEntity> listZyEsItemEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(),ZyEsItemEntity.class,params);
				for (ZyEsItemEntity zyEsItem : listZyEsItemEntitys) {
					zyEsItemService.save(zyEsItem);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
}
